import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

class Request {
    public String username;
    public String password;
}
class Response {
    public boolean ok;
}
@WebServlet("/json")
public class JsonParameter extends HelloServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //此处约定的请求格式：
        //Post/json
        //Content-Type：application/json
        //
        //{
        //  username=zhangsan
        //  password=123
        // }
        ObjectMapper objectMapper = new ObjectMapper();
        Request request = objectMapper.readValue(req.getInputStream(),Request.class);

        System.out.println("username=" + request.username);
        System.out.println("password=" + request.password);
        //此处约定的响应格式为：
        //{
        //  ok:true
        //
        // }
        //把请求的body按照json的格式解析成java对象
        Response response = new Response();
        response.ok = true;
        //把响应转换成一个json字符串
        String respJson = objectMapper.writeValueAsString(response);
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(respJson);
    }
}

